import { Component, Input, OnInit } from '@angular/core';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { MyModalHelper } from '../../../../core/my-modal.helper';
import { GoodsService } from '../../../../core/routes-services/goods.service';
import { QCLOUD_DOMAIN, UPLOAD_DOMAIN } from '../../../../constant/config';
import { CacheService } from '../../../../core/routes-services/cache.service';
import { Router } from '@angular/router';
import { PicViewerModalComponent } from '@shared/pic-viewer-modal/pic-viewer-modal.component';

@Component({
  selector: 'app-step2',
  templateUrl: './step2.component.html',
  styles: [`
    :host ::ng-deep .ant-upload.ant-upload-drag {
      margin-bottom: 20px;
    }
  `],
})
export class Step2Component implements OnInit {
  uploadDomain = UPLOAD_DOMAIN;
  qcloudDomain = QCLOUD_DOMAIN;
  isLoading = false;

  entity: any = {};
  headers: any = {};

  componentDirty: boolean = false;

  @Input() imgList: any[] = [];

  constructor(private router: Router,
              public goodsService: GoodsService,
              private modalHelper: MyModalHelper,
              private cacheService: CacheService,
              private message: NzMessageService) {
  }

  ngOnInit(): void {
    const token: any = this.cacheService.getTokenInfo();
    this.headers = { 'Authorization': token };
    this.entity = this.goodsService.entity;
    // console.log("2222222")
    // console.log(this.entity)
  }


  handlePreview = (file: UploadFile) => {
    this.modalHelper.open(PicViewerModalComponent, { currFile: file, picList: this.imgList }, 660, {
      nzMaskClosable: false,
    }).subscribe(u => {
      console.log(u);
    }, (error) => {
      console.error('弹窗回调出错：', error);
    });
  };


  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      this.componentDirty = true;
    } else if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }
  }

  /**
   * 移除图
   * @param {UploadFile} file
   */
  handleRemove = (file: UploadFile) => {
    this.componentDirty = true;
    this.imgList = this.imgList.filter((img) => img.imgKey != file.imgKey);
    // if (this.entity.mainImg == file.imgKey) {
    //   this.entity.mainImg = null;
    //   this.initValidateForm();
    // }
  };

  beforeUpload = (file: File) => {
    if (this.imgList.length >= 5) {
      this.message.warning('最多只能上传5张商品图');
      return false;
    }
    return true;
  };

  _submit() {
    if (this.imgList.length <= 0) {
      this.message.error('请至少上传一张照片');
      return false;
    }
    this.isLoading = true;

    //构造 商品图
    let goodsImages: any[] = [];
    this.imgList.forEach((t) => {
      goodsImages.push(t.imgKey);
    });
    if (!this.entity.id || this.entity.id == 0) {
      //新增到最后一步再同一保存
      this.goodsService.entity.goodsImages = goodsImages;
      ++this.goodsService.step;
    } else {
      //修改
      if (this.componentDirty) {
        this.goodsService.updateImgs(this.entity.id, { 'goodsImages': goodsImages }).then((res) => {
          if (res.status.toString().startsWith('20')) {
            this.message.success('保存成功');
            ++this.goodsService.step;
          } else {
            this.message.warning(res.message);
          }
          this.isLoading = false;
        }, error => {
          this.message.error(error.message ? error.message : error.error);
          this.isLoading = false;
        });
      } else {
        ++this.goodsService.step;
      }
    }
  }

  prev() {
    --this.goodsService.step;
  }

  goBack() {
    this.goodsService.reset();
    this.router.navigate(['/goods/list']);
  }
}
